import React, { MouseEvent, useState } from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, Flex, message } from "antd";
import "./index.scss";
import { login, register, getUserInfo } from "@/apis/userApi";
import { useDispatch, useSelector } from "react-redux";
import {
  setEmailToStore,
  setShortToken,
  setLongToken,
  setPasswordToStore,
  clearPassword,
  setIsRememberToStore,
  setUserLikesListToStore,
  setUserCollectionList,
  setUserAvatar,
} from "@/store/UserInfo";
import { RootState } from "@/store";
import { useNavigate } from "react-router-dom";

const pageStyle: React.CSSProperties = {
  height: "100%",
  width: "100%",
};

interface GetFieldValueType {
  (fieldName: string): any; // 根据实际情况选择合适的返回类型
}

interface LoginProps {
  email: string;
  password: string;
  repassword?: string;
}

const Login: React.FC = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [isLogin, setIsLogin] = useState(true);
  const [isRemember, setIsRemember] = useState(
    useSelector((state: RootState) => state.UserInfoStore.isRemember)
  );
  const [email] = useState(
    useSelector((state: RootState) => state.UserInfoStore.email)
  );
  const [password] = useState(
    useSelector((state: RootState) => state.UserInfoStore.password)
  );

  const onFinish = async (values: LoginProps) => {
    if (isLogin) {
      // 登录
      const res = await login(values);

      // 如果成功了，就跳转到首页
      // 如果可以走到这里就说明登录成功了
      // 登录成功，设置token
      // dispatch(setToken(res.data?.token ? res.data.token : ""));
      dispatch(setShortToken(res.data?.shortToken || "")); // 设置短 token
      dispatch(setLongToken(res.data?.loginToken || "")); // 设置长 token
      dispatch(setEmailToStore(values.email)); // 设置email到store
      console.log("登录成功, 用户信息", res.data);

      // 判断是否是记住我
      if (isRemember) {
        // 记住我
        console.log("isRemember is true", isRemember);
        // 设置password到store
        dispatch(setPasswordToStore(values.password));
        dispatch(setIsRememberToStore(true));
      } else {
        // 不记住我
        console.log("isRemember is false", isRemember);
        // 清除password
        dispatch(clearPassword());
        dispatch(setIsRememberToStore(false));
      }

      // 获取用户信息
      const userInfoRes = await getUserInfo();

      // 设置用户的点赞列表信息到store
      dispatch(setUserLikesListToStore(userInfoRes.data?.likesList!));

      // 当时为了修改这个用户信息是修改了很多的地方的，这个用户列表返回的是收藏夹不是非常的合理
      // 当时是为了修改这个东西的，但是需要修改的地方有很多所以就没有放弃了。
      // 这里修改的话，需要修改的地方有文章详情这块地方，这里用了这个存储库中的用户收藏夹列表
      // 现在的目的是为了再次尝试修改这些地方
      // 现在后端传回来的数据是
      /* 
        {
          folderName: string;
          collectItem: string[];
          _id: string;
        }[]
      */
      // 但是我需要的数据是这样的
      /* 
        {
          folderName: string;
          collectItem: {
            _id: string;
            title: string;
            summary: string;
          }[];
          _id: string;
        }[]
      */
      // ****************** 等一下写完之后就让后端改一下这个接口 *******************

      // 设置用户的收藏列表信息到store
      dispatch(setUserCollectionList(userInfoRes.data?.collectList!));

      // 设置用户的头像地址到 store 中
      dispatch(setUserAvatar(userInfoRes.data?.avatar!));

      // 回退到上一页
      // 尝试返回到上一页，如果没有上一页则跳转到首页
      // if (window.history.length > 1) {
      //   window.history.back(); // 返回上一页
      // } else {
      //   navigate("/layout");
      //   // window.location.href = "/layout"; // 跳转到首页
      // }
      message.success("登录成功", 1.5, () => {
        navigate("/layout");
      });
    } else {
      // 注册
      const res = await register(values);

      // 如果成功了就会走到这里
      if (res.code === 200) {
        setIsLogin(true);
      }
    }
  };

  const handleTORegister = (event: MouseEvent) => {
    event.preventDefault();
    setIsLogin(!isLogin);
  };

  const usernameRules = [
    { required: true, message: "请输入用户名" },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱格式",
    },
  ];
  const passwordRules = [
    { required: true, message: "请输入密码" },
    { min: 8, message: "密码长度至少为8位" },
    { max: 20, message: "密码长度不能超过20位" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,20}$/,
      message: "密码至少包含大小写字母和数字",
    },
  ];
  const repasswordRules = [
    ...passwordRules,
    ({ getFieldValue }: { getFieldValue: GetFieldValueType }) => ({
      validator(_rule: any, value: any) {
        if (!value || getFieldValue("password") === value) {
          return Promise.resolve();
        }
        return Promise.reject("两次输入的密码不一致!");
      },
    }),
  ];

  return (
    <Flex style={pageStyle} justify="center" align="center">
      {isLogin ? (
        <Form
          name="login"
          initialValues={{
            remember: isRemember,
            email: isRemember ? email : "",
            password: isRemember ? password : "",
          }}
          style={{ maxWidth: 360 }}
          onFinish={onFinish}
        >
          <Form.Item name="email" rules={usernameRules}>
            <Input
              prefix={<UserOutlined />}
              value={email}
              placeholder="请输入用户名"
            />
          </Form.Item>
          <Form.Item name="password">
            <Input
              prefix={<LockOutlined />}
              value={password}
              type="password"
              placeholder="请输入密码"
            />
          </Form.Item>
          <Form.Item>
            <Flex justify="space-between" align="center">
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox
                  checked={isRemember}
                  onChange={(e) => setIsRemember(e.target.checked)}
                >
                  记住我
                </Checkbox>
              </Form.Item>
            </Flex>
          </Form.Item>

          <Form.Item>
            <Button block type="primary" htmlType="submit">
              登录
            </Button>
            还没有账号？
            <a href="" onClick={handleTORegister}>
              去注册
            </a>
          </Form.Item>
        </Form>
      ) : (
        <Form
          name="login"
          initialValues={{ remember: false }}
          style={{ maxWidth: 360 }}
          onFinish={onFinish}
        >
          <Form.Item name="email" rules={usernameRules}>
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="password" rules={passwordRules}>
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="请输入密码"
            />
          </Form.Item>
          <Form.Item name="repassword" rules={repasswordRules}>
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="请再次输入密码"
            />
          </Form.Item>
          <Form.Item>
            <Flex justify="space-between" align="center">
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              {/* <a href="">Forgot password</a> */}
            </Flex>
          </Form.Item>

          <Form.Item>
            <Button block type="primary" htmlType="submit">
              注册
            </Button>
            <a href="" onClick={handleTORegister}>
              去登录
            </a>
          </Form.Item>
        </Form>
      )}
    </Flex>
  );
};

export default Login;
